<template>
  <div class="add-enterprise">
    <header class="add-header">
      <div class="left">
        <span class="arrow" @click="$router.back()"><i class="el-icon-arrow-left" />返回</span>
        <span>|</span>
        <span>{{ id ? '编辑企业' : '添加企业' }}</span>
      </div>
      <div class="right">
        黑马程序员
      </div>
    </header>
    <main class="add-main">
      <div class="form-container">
        <div class="title">企业信息</div>
        <div class="form">
          <el-form ref="ruleFormRef" label-width="100px" :model="addForm" :rules="addFormRules">
            <el-form-item label="企业名称" prop="name">
              <el-input v-model="addForm.name" />
            </el-form-item>
            <el-form-item label="法人" prop="legalPerson">
              <el-input v-model="addForm.legalPerson" />
            </el-form-item>
            <el-form-item label="注册地址" prop="registeredAddress">
              <el-input v-model="addForm.registeredAddress" />
            </el-form-item>
            <el-form-item label="所在行业" prop="industryCode">
              <el-select v-model="addForm.industryCode" placeholder="请选择">
                <el-option
                  v-for="item in industryList"
                  :key="item.industryCode"
                  :label="item.industryName"
                  :value="item.industryCode"
                />
              </el-select>
            </el-form-item>
            <el-form-item label="企业联系人" prop="contact">
              <el-input v-model="addForm.contact" />
            </el-form-item>
            <el-form-item label="联系电话" prop="contactNumber">
              <el-input v-model="addForm.contactNumber" />
            </el-form-item>
            <el-form-item label="营业执照" prop="businessLicenseUrl">
              <el-upload
                v-model="addForm.businessLicenseUrl"
                action="#"
                :file-list="fileList"
                :http-request="getUpload"
                :before-upload="beforeUpload"
              >
                <el-button size="small" type="primary">{{ addForm.businessLicenseUrl ? '已上传':'点击上传' }}</el-button>
                <div slot="tip" class="el-upload__tip">支持扩展名：.png .jpg .jpeg，文件大小不得超过5M</div>
              </el-upload>
            </el-form-item>
          </el-form>
        </div>
      </div>
    </main>
    <footer class="add-footer">
      <div class="btn-container">
        <el-button>重置</el-button>
        <el-button type="primary" @click="confirmSubmit">确定</el-button>
      </div>
    </footer>
  </div>
</template>

<script>
import { createEnterpriseAPI, getEnterpriseDetailAPI, getIndustryListApi, updateEnterpriseAPI, uploadApi } from '@/api/enterprise'
import { validMobile } from '@/utils/validate'
export default {
  data() {
    return {
      addForm: {
        name: '', // 企业名称
        legalPerson: '', // 法人
        registeredAddress: '', // 注册地址
        industryCode: '', // 所在行业
        contact: '', // 企业联系人
        contactNumber: '', // 联系人电话
        businessLicenseUrl: '', // 营业执照url
        businessLicenseId: '' // 营业执照id
      },
      addFormRules: {
        name: [
          { required: true, message: '必填项，内容不能为空', trigger: 'blur' }
        ],
        legalPerson: [
          { required: true, message: '必填项，内容不能为空', trigger: 'blur' }
        ],
        registeredAddress: [
          { required: true, message: '必填项，内容不能为空', trigger: 'blur' }
        ],
        industryCode: [
          { required: true, message: '必填项，内容不能为空', trigger: 'blur' }
        ],
        contact: [
          { required: true, message: '必填项，内容不能为空', trigger: 'blur' }
        ],
        contactNumber: [
          { required: true, message: '必填项，内容不能为空', trigger: 'blur' },
          { validator: validMobile, trigger: ['change', 'blur'] }
        ],
        businessLicenseUrl: [
          { required: true, message: '必填项，内容不能为空', trigger: 'blur' }
        ]
      },
      // 可选行业列表
      industryList: [],
      // 营业执照列表
      fileList: []
    }
  },
  computed: {
    id() {
      return this.$route.query.id
    }
  },
  mounted() {
    this.getindustryList()
    if (this.id) {
      this.getEnterpriseDetail()
    }
  },
  methods: {
    async confirmSubmit() {
      this.$refs.ruleFormRef.validate()
      if (this.id) {
        await updateEnterpriseAPI({ ...this.addForm, id: this.id })
        this.$message.success('编辑成功')
      } else {
        await createEnterpriseAPI(this.addForm)
        this.$message.success('新增成功')
      }
      this.$router.back()
    },
    beforeUpload(file) {
      const allowImgType = ['image/jpeg', 'image/png', 'image/jpg'].includes(file.type)
      const isLt5M = file.size / 1024 / 1024 < 5

      if (!allowImgType) {
        this.$message.error('上传营业执照图片只能是 PNG/JPG/JPEG 格式!')
      }
      if (!isLt5M) {
        this.$message.error('上传营业执照图片大小不能超过 5MB!')
      }
      return allowImgType && isLt5M
    },
    async getindustryList() {
      const res = await getIndustryListApi()
      this.industryList = res.data
    },
    async getUpload(event) {
      // 获取文件的数组对象
      const file = event.file
      console.log(file)

      // 判断
      // 从数组对象中取出第一个文件
      // const data = files[0]
      // 创建formData实例
      const fd = new FormData()
      // 将文件的内容写入到FormData
      fd.append('file', file)
      fd.append('type', 'businessLicense')
      console.log(222)
      // 请求数据
      try {
        const res = await uploadApi(fd)
        console.log(res)
        this.addForm.businessLicenseId = res.data.id
        this.addForm.businessLicenseUrl = res.data.url
        this.fileList.push({
          name: file.name,
          url: res.data.url
        })
        this.$message.success('上传成功')
      } catch (error) {
        this.$message.error('上传失败')
      }

      // 单独校验表单，清除错误信息
      this.$refs.ruleForm.validateField('businessLicenseId')
    },
    async getEnterpriseDetail() {
      const res = await getEnterpriseDetailAPI(this.id)
      const { businessLicenseId, businessLicenseUrl, contact, contactNumber, industryCode, legalPerson, name, registeredAddress } = res.data
      this.addForm = { businessLicenseId, businessLicenseUrl, contact, contactNumber, industryCode, legalPerson, name, registeredAddress }
    }
  }
}
</script>

  <style scoped lang="scss">
  .add-enterprise {
    background-color: #f4f6f8;
    height: 100vh;

    .add-header {
      display: flex;
      justify-content: space-between;
      padding: 0 20px;
      height: 64px;
      line-height: 64px;
      font-size: 16px;
      font-weight: bold;
      background-color: #fff;

      .left {
        span {
          margin-right: 4px;
        }
        .arrow{
          cursor: pointer;
        }
      }

      .right {
        text-align: right;
      }
    }

    .add-main {
      background: #f4f6f8;
      padding: 20px 130px;

      .form-container {
        background-color: #fff;
        .title {
          height: 60px;
          line-height: 60px;
          padding-left:20px;
        }
        .form {
          margin-bottom: 20px;
          padding: 20px 65px 24px;
          .el-form{
            display: flex;
            flex-wrap: wrap;
            .el-form-item{
              width: 50%;
            }
          }
        }
      }
    }

    .add-footer {
      position: fixed;
      bottom: 0;
      width: 100%;
      padding: 24px 50px;
      color: #000000d9;
      font-size: 14px;
      background: #fff;
      text-align: center;
    }
  }
  </style>
